import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:state_management_flutter_bloc/bloc/palyer_list_states.dart';
import 'package:state_management_flutter_bloc/bloc/palyer_listing_bloc.dart';
import 'package:state_management_flutter_bloc/bloc/player_listing_events.dart';
import 'package:state_management_flutter_bloc/models/api_models.dart';
import 'package:state_management_flutter_bloc/models/nation.dart';
import 'package:state_management_flutter_bloc/search_configuration.dart';
import 'package:state_management_flutter_bloc/services/player_repository.dart';
import 'package:state_management_flutter_bloc/themes/themes.dart';
import 'package:state_management_flutter_bloc/widgets/search_bar.dart';

import 'advanced_search_page.dart';
import 'message.dart';

class HomePage extends StatefulWidget {

  final PlayerRepository playerRepository;
  final SearchConfiguration _searchConfiguration = new SearchConfiguration();

  HomePage({this.playerRepository});

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  PlayerListingBloc _playerListingBloc;

  @override
  void initState() {
    super.initState();
    _playerListingBloc =
        PlayerListingBloc(playerRepository: widget.playerRepository);
  }

  @override
  void dispose() {
    super.dispose();
    _playerListingBloc.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      builder:(context)=> _playerListingBloc,
      child: Scaffold(
        floatingActionButton: FloatingActionButton.extended(onPressed: () async{
          var search = await Navigator.of(context).push(MaterialPageRoute(builder: (context)=>
          AdvancedSearchPage(searchConfiguration: widget._searchConfiguration,)));
         var query = search["search_configuration"];

          _playerListingBloc.dispatch(SearchAdvanceEvent(query));
        }, label: Text('高级查询', style: TextStyle(fontSize: 20),),
        icon: Icon(Icons.filter_list),),
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            'Football Players',
          ),
        ),
        body: Column(
          children: <Widget>[
            HorizontalBar(),
            SizedBox(
              height: 10.0,
            ),
            SearchBar(),
            SizedBox(
              height: 10.0,
            ),
            PlayerListing(),
          ],
        ),
      ),
    );
  }
}

class HorizontalBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80.0,
      child: ListView.builder(
        itemBuilder: builderItem,
        itemCount: homePageNations.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  Widget builderItem(context, index) {
    return InkWell(
      onTap: () {
        BlocProvider.of<PlayerListingBloc>(context)
            .dispatch(CountrySelectedEvent(nationModel: homePageNations[index]));
      },
      child: Container(
        width: 70.0,
        height: 70.0,
        decoration: BoxDecoration(
            shape: BoxShape.circle,
            image:
                DecorationImage(image: AssetImage(homePageNations[index].imagePath))),
        margin: EdgeInsets.symmetric(horizontal: 16.0),
      ),
    );
  }
}

class PlayerListing extends StatefulWidget {
  @override
  _PlayerListingState createState() => _PlayerListingState();
}

class _PlayerListingState extends State<PlayerListing> {
  ScrollController _playerViewListScrollController;
  @override
  void initState() {
    _playerViewListScrollController = ScrollController(keepScrollOffset: true);
    _playerViewListScrollController.addListener((){
      if(_playerViewListScrollController.position.maxScrollExtent == _playerViewListScrollController.offset){
        BlocProvider.of<PlayerListingBloc>(context).dispatch(PlayerListLoadMoreEvent());
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _playerViewListScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder(
        bloc: BlocProvider.of<PlayerListingBloc>(context),
        builder: (context, state) {
          if (state is PlayerUninitializedState) {
            return Message(message: "请选择一个国家获取球员");
          } else if (state is PlayerEmptyState) {
            return Message(message: "没有球员");
          } else if (state is PlayerErrorState) {
            return Message(
              message: "出错了",
            );
          } else if (state is PlayerFetchingState) {
            return Expanded(
              child: Center(
                child: CircularProgressIndicator(),
              ),
            );
          } else if (state is PlayerFetchedState) {
            var players = state.players;
            return Expanded(
                child: buildPlayersList(players),
            );
          } else if (state is PlayerListLoadingMoreState) {
            return Expanded(
              child: Stack(children: <Widget>[
                buildPlayersList(state.players),
                Positioned(
                  bottom: 10,
                  child: CircularProgressIndicator(
                    strokeWidth: 3,
                  ),
                ),
              ],
              fit: StackFit.expand,
              alignment: AlignmentDirectional.center),
            );
          } else {
            return Container();
          }
        });
  }

  Widget buildPlayersList(List<Players> players) {
    return ListView.separated(
      itemBuilder: (context, index) {
        Players player = players[index];
        return ListTile(
          leading: Image.network(
            player.headshot.imgUrl,
            width: 70,
            height: 70,
          ),
          title: Text(
            player.name,
            style: titleStyle,
          ),
          trailing: Text(
            player.rating.toString()+" "+player.position,
            style: titleStyle,
          ),
          subtitle: Text(
            "${player.club.name}|${player.league.name}|${player.nation.name}",
            style: subTitleStyle,
          ),
        );
      },
      separatorBuilder: (context, index) {
        return Divider(
          height: 8.0,
          color: Colors.blue[100],
        );
      },
      itemCount: players.length,
      controller: _playerViewListScrollController,
    );
  }
}
